home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 1181 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.3 KB

  1. Path: news.iag.net!news
  2. From: jatmon@iag.net (John R Buchan)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: pseudo-random numbers
  5. Date: 11 Jan 1996 17:49:51 GMT
  6. Organization: Internet Access Group, Orlando, Florida
  7. Message-ID: <4d3ijv$9fl@news.iag.net>
  8. References: <17709D420S86.JJSTEP00@ukcc.uky.edu>
  9. NNTP-Posting-Host: pm3-orl4.iag.net
  10. X-Newsreader: WinVN 0.99.7
  11.  
  12. In article <17709D420S86.JJSTEP00@ukcc.uky.edu>, JJSTEP00@ukcc.uky.edu says...
  13. >
  14. >I know what the c.l.c. FAQ says about pseudo-random numbers, so I wonder why
  15. >I seem to get "better" results with "rand() % n + 1" than I get when I use
  16. >"n * rand() / RAND_MAX + 1"  Am I missing some parenthesis or something?
  17.  
  18. I don't know what type you have defined n as, but I'll bet that it is an
  19. integer of some type.  I can see two like problems.
  20.  
  21.   1. n * rand() exceeds the limits of int (the return type of rand) and/or
  22.      n's type.
  23.  
  24.   2. Integer math is being performed. So any fractional part of the answer
  25.      is being truncated. 
  26.  
  27. One solution, suggested in the faq <polite jab>, is:
  28.  
  29.    (int)((double)rand() / ((double)RAND_MAX + 1) * N)
  30.  
  31. This forces floating point math and casts the result back to an int. I'll
  32. leave any adjustments to you.
  33.  
  34. -- 
  35. John R Buchan           -:|:-     Looking for that elusive FAQ?  ftp to:
  36. jatmon@mail.iag.net     -:|:-     rtfm.mit.edu /pub/usenet-by-group/....
  37.  
  38.